import {
    axios
} from '../../utils/ajax.js'
import {
    gettime
} from '../../utils/djs.js'
import {
    checklogin
} from '../../utils/login.js'
let app = getApp()
Page({
    data: {
        //返回顶部标识
        totopshow: false,
        //模板
        template: '',
        //秒杀时间
        time: [],
        //秒杀定时器
        timer: '',
        //总楼层数
        totlefloor: '',
        //当前楼层数
        curfloor: '1',
        btnstate: '',
        //存放滚动历史数值
        pageTop: 0,
        //vip信息
        isVip: '',
        //头部广告轮播
        newslist: '',
        //用户名
        username: '',
        userid: '',
        token: '',
        windowWidth: '',
        currentCatId: 0,
        showMore: false,
        hideTop: false,
        x: 0,
        hasNetwork: true
    },
    onShow: function() {
        this.setData({
            windowWidth: app.globalData.windowWidth,
            isFirst: app.globalData.isFirst
        })

        wx.getNetworkType({
            success: res => {
                if (res.networkType == 'none') {
                    this.setData({
                        hasNetwork: false
                    })
                }
            }
        })

        wx.onNetworkStatusChange(res => {
            if (!res.isConnected) {
                this.setData({
                    hasNetwork: false
                })
            }
        })

        this.getHomeData()
    },

    onLoad: function() {
        this.getNewsData()
    },

    getHomeData: function() {
        axios({
            url: '/goods/home',
            data: {
                userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
                token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null
            }
        }).then((res) => {
            // console.log(res.data)
            let navlist = res.data.catList;
            navlist.unshift({
                catId: 0,
                catName: '推荐'
            })
            this.setData({
                template: res.data.templates,
                recommendList: res.data.data,
                navlist: navlist,
                currentCatId: this.data.currentCatId,
                isVip: res.data.isVip,
                hasMsg: res.data.hasMsg,
                notice: res.data.notice ? res.data.notice : null
            })
            layout(res.data.catList, this)
            let nexttime = this.data.template.find(x => x.tType == 2) ? this.data.template.find(x => x.tType == 2).items[0].seckillNextTime : 0
            this.secondkilltimer(nexttime)
            this.data.timer = setInterval(() => {
                this.secondkilltimer(nexttime)
            }, 1000)
        })
    },

    getNewsData: function() {
        axios({
            url: '/home/newslist',
            data: {
                userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
                token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null
            }
        }).then((res) => {
            // console.log(res)
            this.setData({
                newslist: res.data.newslist && res.data.newslist.length > 0 ? res.data.newslist : null,
                newsanimate: true,
                news: res.data.newslist && res.data.newslist.length > 0 ? res.data.newslist[0] : null
            })
            if (this.data.newslist) {
                let newsNum = 0;
                let newsCount = setInterval(() => {
                    newsNum = newsNum + 1;
                    if (newsNum > this.data.newslist.length - 1) {
                        newsNum = 0;
                    }
                    this.setData({
                        newsanimate: false,
                        news: this.data.newslist[newsNum] ? this.data.newslist[newsNum] : {}
                    }, () => {
                        this.setData({
                            newsanimate: true
                        })
                    })
                }, 15000)
            }
        })
    },

    changeTab: function(e) {
        let catId = e.currentTarget.dataset.catId;
        if (this.data.currentCatId != catId) {
            this.setData({
                currentCatId: catId,
                showMore: false
            })
            layout(this.data.navlist, this)
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 0
            })
            if (catId == 0) {
                this.setData({
                    goodslist: []
                })
            } else {
                getCatGoodsData(catId, this)
            }
        }
    },

    fresh: function() {
        wx.getNetworkType({
            success: res => {
                if (res.networkType != 'none') {
                    this.setData({
                        hasNetwork: true
                    })
                    this.getHomeData()
                    this.getNewsData()
                }
            }
        })
    },
    // 下拉刷新
    onPullDownRefresh: function() {
        let catId = this.data.currentCatId;
        if (catId == 0) {
            //再次请求首页数据
            axios({
                url: '/goods/home',
                data: {
                    userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
                    token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null
                }
            }, false).then((res) => {
                wx.stopPullDownRefresh()
                //首页数据
                // console.log(res.data)
                this.setData({
                    template: res.data.templates,
                    // recommendList: res.data.data,
                    // navlist: res.data.catList,
                    // currentCatId: res.data.catList[0].catId,
                    isVip: res.data.isVip
                })
                let nexttime = this.data.template.find(x => x.tType == 2) ? this.data.template.find(x => x.tType == 2).items[0].seckillNextTime : 0
                this.secondkilltimer(nexttime)
                this.data.timer = setInterval(() => {
                    this.secondkilltimer(nexttime)
                }, 1000)
            })
        } else {
            getCatGoodsData(catId, this)
        }
    },

    //返回顶部
    onPageScroll(e) {
        // console.log(e.scrollTop)
        this.setData({
            totopshow: e.scrollTop > 400 ? true : false
        })
        if (e.scrollTop > 178) {
            if (this.data.hideTop == false) {
                this.setData({
                    hideTop: true
                })
            }
        } else {
            if (this.data.hideTop == true) {
                this.setData({
                    hideTop: false
                })
            }
        }
    },
    //定时器
    secondkilltimer(val) {
        if (gettime(val, 2)) {
            this.setData({
                time: [gettime(val, 2).h, gettime(val, 2).m, gettime(val, 2).s]
            })
        } else {
            clearInterval(this.data.timer)
            this.setData({
                time: ['00', '00', '00']
            })
        }
    },
    onShareAppMessage: function(res) {
        return {
            title: '淘集集',
            path: '/pages/home/home',
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },
    //去会员中心
    govipcenter() {
        checklogin().then((res) => {
            // console.log(res)
            wx.navigateTo({
                url: `../my/vipcenter/vipcenter`,
            })
        })
    },
    // 模板跳转
    onTemplateTap: function(e) {
        let {
            type,
            linkId,
            title = '',
            where = ''
        } = e.currentTarget.dataset;
        // console.log('home:', type, linkId, title,where);

        switch (parseInt(type)) {
            // 商品
            case 0:
                wx.navigateTo({
                    url: `goodsDetail/goodsDetail?linkId=${linkId}&title=${title}`
                });
                break;
                // 专题
            case 1:
                wx.navigateTo({
                    url: `zone/zone?linkId=${linkId}&title=${title}`
                });
                break;
                // 分类
            case 6:
                wx.navigateTo({
                    url: `category/category?linkId=${linkId}&title=${title}`
                });
                break;
                // 活动
            case 2:
                wx.navigateTo({
                    url: `/pages/webview/webview?linkId=${linkId}`
                });
                break;
            default:
                return;
        }

        if (where === 'notice') {
            this.hideNotice();
        }
    },

    hideNotice: function() {
        this.setData({
            isFirst: false
        })
        app.globalData.isFirst = false;
    },

    onReachBottom: function() {
        let catId = this.data.currentCatId;
        if (catId != 0) {
            if (this.data.page > 0) {
                getCatGoodsMore(catId, ++this.data.page, this)
            }
        }
    },

    toMyCenter: function() {
        console.log(wx.getStorageSync("userinfo"))
        if (wx.getStorageSync("userinfo") && wx.getStorageSync("userinfo").userid > 0) {
            wx.navigateTo({
                url: '/pages/my/my'
            })
        }
    },

    toMsg: function() {
        if (wx.getStorageSync("userinfo") && wx.getStorageSync("userinfo").userid > 0) {
            wx.navigateTo({
                url: '/pages/home/messagecenter/dealnews/dealnews'
            })
        }
    },

    showMore: function() {
        this.setData({
            showMore: true
        })
    },

    hideMore: function() {
        this.setData({
            showMore: false
        })
    },

    prevent: () => {}
})

function getCatGoodsMore(catId, page, that) {
    axios({
        url: '/goods/category',
        data: {
            catId: catId,
            page: page,
            userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
            token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null
        }
    }).then(res => {
        // console.log(res.data)
        that.setData({
            goodslist: that.data.goodslist.concat(res.data.data),
            page: res.data.data && res.data.data.length > 0 ? page : 0,
            // totalpages: res.data.totalpages,
            canload: res.data.data && res.data.data.length > 0 ? true : false
        })
    })
}

function getCatGoodsData(catId, that) {
    axios({
        url: '/goods/category',
        data: {
            catId: catId,
            page: 1,
            userid: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').userid : null,
            token: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').token : null
        }
    }).then(res => {
        // console.log(res.data)
        wx.stopPullDownRefresh()
        that.setData({
            goodslist: res.data.data,
            page: 1,
            // totalpages: res.data.totalpages,
            canload: res.data.data && res.data.data.length == 30 ? true : false
        })
    })
}

function layout(navlist, that) {
    let navWidth = 0,
        curNavWidth = 0,
        curIndex = navlist.findIndex(item => item.catId == that.data.currentCatId);

    navlist.forEach((item, index) => {
        if (that.data.currentCatId == item.catId) {
            navWidth += item.catName.length * 32 + 44;
        } else {
            navWidth += item.catName.length * 30 + 44;
        }
        if (index < curIndex) {
            curNavWidth += item.catName.length * 15 + 22;
        }
    })

    curNavWidth = curNavWidth - 160 <= 0 ? 0 : curNavWidth - 160;

    that.setData({
        navWidth: navWidth,
        x: -curNavWidth
    })
}